/**
 * 漏斗专题图
 * 说明：多分组或所指标时适合展示数据构成情况
 */
/*
data: [{
  id: 'radar',
  name: '漏图图',
  regioncode: "aaa",
  regionname: "aaa",
  max: 100,
  lon: "0.92866163503169",
  lat: "30.830660058696104",
  showThumbnails:false,
  width: '100px',
  height: '100px',
  color: ['#029BDA', '#3B478F', '#8593D0', '#51C1E7', '#24C39D'],
  data: [{
      value: [0, 0, 0, 100, 99, 100, 0, 0],
      name: '直接访问'
    },
    {
      value: [0, 0, 0, 99, 99, 99, 0, 0],
      name: '邮件营销'
    },
    {
      value: [0, 0, 0, 60, 60, 59, 0, 0],
      name: '联盟广告'
    },
    {
      value: [0, 0, 0, 39, 40, 40, 0, 0],
      name: '视频广告'
    },
    {
      value: [0, 0, 0, 20, 20, 19, 0, 0],
      name: '搜索引擎'
    }
  ]
}]
*/

import echarts from 'echarts'; // echarts 文件引入
import sgisLayerBase from '../../sfgis.layer.base';
import styleModify from './echarts.stylemodify'; // 为了设置图层的透明度，可见性，zIndex引入函数
import colorPicker from './echarts.colorpicker'; // 颜色初始化配置文件
export default {
  activeMap: {}, // 当前活动地图
  radarLayer: '',
  radarLayerInfo: {}, // 图层其他相关信息
  initIndicator(data) {
    const indicator = [];
    for (let i = 0; i < 8; i++) {
      indicator.push({
        name: 'radar' + i,
        max: data.max
      });
    } // indicator计算
    return indicator;
  },
  calRadarData(data) {
    const datas = [];
    for (const key in data) {
      datas.push({
        value: data[key].value,
        name: data[key].name,
        symbol: 'circle',
        symbolSize: 1,
        label: {
          show: true,
          position: [-5, -10],
          formatter(point) {
            return '';
          }
        },
        tooltip: {
          formatter() {
            return data[key].name + ':' + data[key].value[4];
          }
        },
        itemStyle: {
          borderWidth: 0
        }
      });
    }
    return datas;
  },
  /**
   * 创建地图饼图专题图
   */
  createLayer(map, data) {
    if (!map) {
      return;
    }
    if (!data || !data.data.length) {
      return;
    }
    this.activeMap = map;
    const radarMarkers = this.createMarker(data.data,map); // 创建好所有marker
    const radarLayer = radarMarkers;
    // const radarLayer = L.layerGroup(radarMarkers)
    //   .addTo(map);
    styleModify.onZoom(this.activeMap, radarMarkers); // 为markers绘图添加缩放监听改变z-Index，由于markers的zIndex会随着纬度变化而变化;
    // 此处必须先把容器加到地图上才能加载图表
    this.radarLayer = radarLayer;
    // 将容器加载到地图容器
    this.createCharts(radarMarkers, data.data);
    // 自定义颜色开始
    const id = "radar_chart_" + data.id + "_" + +new Date();
    // 设置容器初始ZINdex,为后面调整图层顺序功能 开始
    styleModify.setLayerOrder(styleModify.curZindex, radarLayer, id);
    styleModify.layerOrder[id] = styleModify.curZindex;
    styleModify.curZindex -= 1;
    // 设置容器初始ZINdex,为后面调整图层顺序功能 结束
    radarLayer.setCustomColor = this.setCustomColor;
    radarLayer.setOpacity = styleModify.setOpaticty; // 设置图层透明度
    radarLayer.setVisible = styleModify.setVisible; // 设置图层可见性
    radarLayer.setZIndexOffset = this.setZIndexOffset; // 设置调整图层顺序函数;
    radarLayer.autoCalgraph = this.autoCalgraph;
    radarLayer.layerId = id;
    radarLayer.charts = [...this.charts];
    // 自定义颜色结束
    const radarLayerInfo = {
      name: data.name,
      layerId:id,
      type: "radar",
      show: data.showThumbnails !== false,
      layer: radarLayer,
      html: this.calgraph(id)
    };
    this.radarLayerInfo = radarLayerInfo;
    sgisLayerBase.setOverLayers(radarLayerInfo);
    return radarLayerInfo;
  },
  calColor(len) {
    const color = [];
    for (let i = 0; i < len; i++) {
      color.push(colorPicker.radar.color[i % 14]);
    }
    return color;
  },
  /**
   * 创建echarts容器
   */
  createMarker(datas,map) {
    const resultMarkers = [];
    for (let i = 0; i < datas.length; i++) {
      const time = +new Date();
      // 初始化最小宽高开始
      const data = datas[i];
      let width = colorPicker.size;
      if (data.hasOwnProperty('width')) {
        width = data.width.slice(0, -2);
        width = parseInt(width);
        if (width < colorPicker.size) {
          width = colorPicker.size;
        }
      }
      let height = colorPicker.size;
      if (data.hasOwnProperty('height')) {
        height = data.width.slice(0, -2);
        height = parseInt(height);
        if (height < colorPicker.size) {
          height = colorPicker.size;
        }
      }
      const iconWidth = width + 45;
      const iconHeight = height + 45;
      // 初始化最小宽高结束
      var el = document.createElement('div');
      el.className = "radar_chart_" + i + time;
      el.id = "radar_chart_" + i + time;
      el.style.width = iconWidth + 'px';
      el.style.height = iconHeight + 'px';
      const chartMarker = new mapboxgl.Marker(el)
        .setLngLat([data.lon, data.lat])
        .addTo(map);
      // const chartMarker = L.marker([datas[i].lat, datas[i].lon], {
      //   id: "radar_chart_" + i + time, // 生成id
      //   pane: styleModify.pane, // 为设置自定义的图层顺序特别设定
      //   icon: L.divIcon({
      //     className: "",
      //     iconSize: [width, height],
      //     html: `
      //     <div id="radar_chart_${i}${time}" style="width:${width}px;height:${height}px;position:relative;background-color:transparent;z-index='99998';">
      //     </div>
      //     `
      //   })
      // });
      resultMarkers.push(chartMarker);
    }

    return resultMarkers;
  },
  /**
   * 创建图表
   * @param {Object} radarMarkers 图表容器
   * @param {Object} datas 数据
   */
  createCharts(radarMarkers, datas) {
    const charts = [];
    for (let i = 0; i < datas.length; i++) {
      const chart = echarts.init(document.getElementById(radarMarkers[i]._element.id));
      const data = datas[i];
      this.graph = [];
      const chartOption = {
        color: datas[i].color ? datas[i].color : (this.calColor(datas[i].data.length)),
        tooltip: {},
        radar: {
          name: {
            show: false,
            textStyle: {
              color: '#fff',
              backgroundColor: '#333',
              borderRadius: 3,
              borderWidth: 0,
              padding: [3, 5]
            }
          },
          indicator: this.initIndicator(datas[i]),
          center: ['50%', '20%'],
          radius: '100%',
          axisLine: {
            show: false
          },
          splitLine: {
            show: false
          },
          splitArea: {
            show: false
          }
        },
        series: [{
          type: 'radar',
          areaStyle: {
            opacity: 1,
            shadowBlur: 1,
            shadowColor: 'rgba(0,0,0,.5)'
          },
          emphasis: {
            areaStyle: {
              // color: 'red'
            }
          },
          data: this.calRadarData(datas[i].data)
        }],
        itemStyle: {
          emphasis: {
            show: false,
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      };
      chart.setOption(chartOption);
      charts.push({
        id: radarMarkers[i]._element.id,
        echart: chart
      });
      // 自定图例样式开始
      const colors = data.color ? data.color : colorPicker.color;
      for (const key in data.data) {
        const index = key % colors.length;
        const color = colors[index];
        this.graph.push({
          name: data.data[key].name,
          color
        });
      }
      // 自定图例样式结束
    }
    this.charts = charts;
  },
  /**
   * 设置自定义漏斗每层颜色
   * par{
   * radarStyle: ['color', 'color', 'color', 'color', 'color'] //金字塔数组颜色
   * }
   */
  setCustomColor(layers, pars) {
    const par = {
      ...pars,
      radarStyle: pars.colors
    };
    for (const key in layers.charts) {
      const item = layers.charts[key];
      const option = item.echart.getOption();
      // 设置金字塔柱状颜色开始
      if (par.hasOwnProperty('radarStyle')) {
        option.color = par.radarStyle;
      }
      // 设置金字塔柱状颜色结束
      item.echart.setOption(option);
      // 自定义图例样式 开始
      // 自定图例样式开始
      const data = option.series[0].data;
      const colors = item.echart.getOption().color;
      this.graph = [];
      for (const key in data) {
        const color = colors[key % colors.length];
        this.graph.push({
          name: data[key].name,
          color
        });
      }
      // 自定图例样式结束
      // 自定义图例样式 结束
    } // 设置自定义漏斗每层颜色
    this.autoCalgraph(layers.layerId);
  },
  /* *设置图例样式 开始 */
  /**
   * @param {string} layerId 图层id
   */
  calgraph(layerId) {
    let html = `<div style="padding:6px" class="${layerId}">`;
    for (const key in this.graph) {
      html += `<div class='chart_item'>
        <div style = 'display:inline-block;width:8px;height:8px;margin:4px 0;padding:0;background:${this.graph[key].color};transform: rotate(45deg);'> 
        
        </div>
        <p>${this.graph[key].name}</p>
      </div>`;
    }
    html += '</div>';
    return html;
  },
  /**
   * @param {string} layerId 图层id
   */
  autoCalgraph(layerId) {
    let html = `<div style="padding:6px" class="${layerId}">`;
    for (const key in this.graph) {
      html += `<div class='chart_item'>
        <div style = 'display:inline-block;width:8px;height:8px;margin:4px 0;padding:0;background:${this.graph[key].color};transform: rotate(45deg);'>
        
        </div>
        <p>${this.graph[key].name}</p>
      </div>`;
    }
    html += '</div>';
    const layers = sgisLayerBase.overLayers;
    for (const key in layers) {
      if (layers[key].layerId === layerId) {
        layers[key].html = html;
      }
    }
    // sgisLayerBase.layerControlChange();
  },
  /* *设置图例样式 结束 */
  /** 设置调整图层顺序函数*/
  setZIndexOffset(index) {
    styleModify.setZIndexOffset(index, this.layerId, this._layers);
  }
};
